﻿var argv=process.argv;
var bindhost=argv[2];//--0.0.0.0
var bindport=argv[3];//--53
var targethost=argv[4];//--8.8.8.8
var targetport=argv[5];//--53
var firadio=require('firadio');
//===================================
process.title='UDP端口转发器['+bindport+']TO['+targethost+':'+targetport+']';
var stdin=process.openStdin();
stdin.setEncoding('binary');
stdin.on('data',function(chunk){
	var chunk_len=chunk.length-2;
	chunk=firadio.gbk_to_utf8(chunk.substr(0,chunk_len));
	if(chunk=='exit'){
		process.exit();
	}
	process.stdout.write('data:['+chunk+']('+chunk_len+")\r\n");
});
stdin.on('end',function(){
	process.stdout.write('end');
});
//===================================
var dgram=require('dgram');
var udp4_bind=dgram.createSocket("udp4");
udp4_bind.on("message",function(msg,rinfo){
	//第一步：收到客户端发来的数据
	var client_address=rinfo.address;
	var client_port=rinfo.port;
	var udp4_target=dgram.createSocket("udp4");
	udp4_target.send(msg,0,msg.length,targetport,targethost,function(err,bytes){
		//第二步：给目标服务器发送数据
		firadio.log('in[ '+client_address+':'+client_port+' ] to [ '+targethost+':'+targetport+' ] bytes: '+bytes);
		//udp4_target.close();
	});
	udp4_target.on("message",function(msg,rinfo){
		//第三步：从目标服务器接收数据
		udp4_bind.send(msg,0,msg.length,client_port,client_address,function(err,bytes){
			//第四步：把收到的数据发回给客户端
			firadio.log('out[ '+rinfo.address+':'+rinfo.port+' ] to [ '+client_address+':'+client_port+' ] bytes: '+bytes);
			//udp4_bind.close();
		});
	});
	udp4_target.on("error", function (err) {
		firadio.log(err);
	});
});
udp4_bind.on("listening", function () {
	var address=udp4_bind.address();
	firadio.log("client listening " +address.address + ":" + address.port);
});
udp4_bind.on("error", function (err) {
	firadio.log(err);
});
udp4_bind.bind(bindport,bindhost);
